// --------------------------
// equipment/EquipmentData.ts // 玩家装备数据类
// --------------------------
import { Equipment, IEquipment } from "./Equipment";
import {  EquipmentConfig } from "../Config/EquipmentConfig";
import { EPlayerType, EWuxing } from "../Config/Enum";
import { EAffixType, EEquipmentType } from "./Item";


// 玩家装备数据类
export class EquipmentData {
    // 已装备的装备（按部位）
    public equipped: Map<string, Equipment> = new Map();
    
    // 背包中的装备
    public inventory: Equipment[] = [];
    
    // 当前玩家类型
    private playerType: EPlayerType;



    constructor(playerType: EPlayerType) {
        this.playerType = playerType;
        this.loadInitialEquipment();
    }

    // 序列化数据用于存储
    getPackage(): any {
        return {
            playerType: this.playerType,
            equipped: Array.from(this.equipped.entries()).map(([slot, equipment]) => [

                slot,
                equipment.getPackage()
            ]),
            inventory: this.inventory.map(equipment => equipment.getPackage())
        };
    }

        // 从序列化数据恢复
    setPackage(data: any): void {
        console.log("equipmentdata setPackage", data);
        if (!data) return;
        
        this.playerType = data.playerType || this.playerType;
        
        // 恢复装备的装备
        this.equipped = new Map();
        if (Array.isArray(data.equipped)) {
            for (const [slot, equipmentData] of data.equipped) {
                const equipment = new Equipment(null); // 创建空装备
                equipment.setPackage(equipmentData);   // 从数据恢复
                this.equipped.set(slot, equipment);
            }
        }
        
        // 恢复背包中的装备
        this.inventory = [];
        if (Array.isArray(data.inventory)) {
            for (const equipmentData of data.inventory) {
                const equipment = new Equipment(null); // 创建空装备
                equipment.setPackage(equipmentData);   // 从数据恢复
                this.inventory.push(equipment);
            }
        }
    }



    // 加载初始装备
    private loadInitialEquipment() {
        // 根据玩家类型加载初始装备
        const initialEquipments = this.getInitialEquipmentForPlayer();
        
        for (const equip of initialEquipments) {
            this.equip(equip);
        }
    }

    // 获取玩家初始装备
    private getInitialEquipmentForPlayer(): Equipment[] {
        let weapon: Equipment;
        // 这里可以根据玩家类型返回不同的初始装备
        // 示例：所有玩家初始都有一把基础武器
        switch (this.playerType) {
            case EPlayerType.Shaolin:
                weapon = new Equipment(EquipmentConfig["blade_01"]);
                break;
            case EPlayerType.Tangmen:
                weapon = new Equipment(EquipmentConfig["dagger_01"]);
                break;
            case EPlayerType.Emei:
                weapon = new Equipment(EquipmentConfig["sword_01"]);
                break;
            case EPlayerType.Gaibang:
                weapon = new Equipment(EquipmentConfig["staff_01"]);
                break;
            case EPlayerType.Wudang:
                weapon = new Equipment(EquipmentConfig["sword_02"]);
                break;
            default:
                weapon = new Equipment(EquipmentConfig["sword_01"]);
                break;
        }
        
        // const weapon = new Equipment(EquipmentConfig["weapon_001"]);
        // const armor = new Equipment(EquipmentConfig["armor_001"]);
        
        return [weapon];
    }

    // 装备一件装备
    public equip(equipment: Equipment): boolean {
        // 检查是否已装备同类型装备
        if (this.equipped.has(equipment.equipmentType)) {
            // 先卸下原有装备
            this.unequip(equipment.equipmentType);
        }
        
        // 装备新装备
        equipment.isEquipped = true;
        this.equipped.set(equipment.equipmentType, equipment);
        return true;
    }

    // 卸下装备
    public unequip(equipmentType: string): Equipment | null {
        const equipment = this.equipped.get(equipmentType);
        if (equipment) {
            equipment.isEquipped = false;
            this.equipped.delete(equipmentType);
            this.addToInventory(equipment);
            return equipment;
        }
        return null;
    }

    // 添加到背包
    public addToInventory(equipment: Equipment) {
        this.inventory.push(equipment);
    }

    // 从背包移除
    public removeFromInventory(equipment: Equipment) {
        const index = this.inventory.indexOf(equipment);
        if (index !== -1) {
            this.inventory.splice(index, 1);
        }
    }

    // // 计算装备总属性（整合所有装备属性）
    // public calculateTotalEquipmentStats(){
    //     // 计算所有装备的普通词缀总属性
    //     this.calculateNormalAffixesTotalStats();
    //     // 计算所有装备的五行词缀总属性
    //     this.calculateWuxingAffixesTotalStats();
    // }



        // 确保五行词缀是最新激活状态
        //this.activateWuxingAffixes();
        // 计算所有五行词缀的总属性

    // calculateTotalEquipmentStats(): Record<EAffixType, number> {
    //     const totalStats: Record<EAffixType, number> = {} as any;
    //     console.log("Calculating total equipment stats...",this.equipped.values());
    //     // 累加所有装备的属性
    //     for (const equipment of this.equipped.values()) {
    //         console.log("Calculating total equipment stats, Calculating stats for equipment:", equipment);

    //         // 计算单件装备的总属性
    //         const stats = equipment.calculateTotalStats();
    //         console.log(`Stats for ${equipment.id}:`, stats);
            

    //         for (const type of Object.keys(stats)) {
    //             const affixType = type as EAffixType;
    //             const value = stats[affixType];
    //             if (!totalStats[affixType]) {
    //                 totalStats[affixType] = 0;
    //             }
    //             totalStats[affixType] += value;
    //         }
    //     }
    //     // 累加背包中的装备属console
    //         console.log("totalStats:", totalStats);
    //         return totalStats;
    // }
calculateTotalEquipmentStats(): {
    normalStats: Record<EAffixType, number>,
    wuxingStats: {}
} {
    const normalStats: Record<EAffixType, number> = {} as any;
    // const wuxingStats: Record<EAffixType, number> = {} as any;
    //const normalStats= {};
    const wuxingStats= {};

    //初始化所有属性类型
    const affixTypeKeys = Object.keys(EAffixType) as (keyof typeof EAffixType)[];
    affixTypeKeys.forEach(key => {
        const type = EAffixType[key];
        normalStats[type] = 0;
        //wuxingStats[type] = 0;
    });

    console.log("计算装备总属性...", this.equipped.values());

    // 累加所有装备的属性
    for (const equipment of this.equipped.values()) {
        console.log("计算装备:", equipment.name);
        const stats = equipment.calculateTotalStats();
        console.log(`装备 ${equipment.name} 的属性:`, stats);

        // 累加普通词缀
        for (const type of Object.keys(stats.normalStats)) {
            const affixType = type as EAffixType;
            const value = stats.normalStats[affixType];
            //normalStats[affixType]=0
            normalStats[affixType] += value;
        }

        // 累加五行词缀
        for (const type of Object.keys(stats.wuxingStats)) {
            const affixType = type as EAffixType;
            const value = stats.wuxingStats[affixType];
            //wuxingStats[affixType]=0
            wuxingStats[affixType] += value;
        }
    }

    console.log("总普通词缀属性:", normalStats);
    console.log("总五行词缀属性:", wuxingStats);
    
    return { normalStats, wuxingStats };
}


    // calculateWuxingAffixesTotalStats(): Record<EWuxingAffixType, number> {
    //     const totalStats: Record<EWuxingAffixType, number> = {} as any;
    //     console.log("Calculating total wuxing affix stats...",this.equipped.values());
    //     // 累加所有装备的五行词缀属性
    //     for (const equipment of this.equipped.values()) {
    //         console.log("Calculating wuxing affix stats for equipment:", equipment);

    //         // 计算单件装备的五行词缀总属性
    //         const stats = equipment.calculateWuxingAffixStats();
    //         console.log(`Wuxing affix stats for ${equipment.id}:`, stats);
            

    //         for (const type of Object.keys(stats)) {
    //             const affixType = type as EWuxingAffixType;
    //             const value = stats[affixType];
    //             if (!totalStats[affixType]) {
    //                 totalStats[affixType] = 0;
    //             }
    //             totalStats[affixType] += value;
    //         }
    // }




        // 激活五行词缀
    public activateWuxingAffixes(): void {
        console.log("开始激活五行词缀...");
        
        // 先重置所有五行词缀为未激活状态
        this.resetAllWuxingAffixes();
        
        // 激活防具循环的相生关系
        this.activateArmorCycle();
        
        // 激活饰品循环的相生关系  
        this.activateAccessoryCycle();
        
        // 激活跨循环的相生关系
        this.activateCrossCycle();
        
        console.log("五行词缀激活完成");
    }

        // 重置所有五行词缀为未激活状态
    private resetAllWuxingAffixes(): void {
        for (const equipment of this.equipped.values()) {
            if (equipment.affixes_wuxing) {
                for (const affix of equipment.affixes_wuxing) {
                    affix.isActive = false;
                }
            }
        }
    }

        // 防具循环：鞋子 -> 裤子 -> 腰带 -> 衣服 -> 帽子 -> 鞋子
    private activateArmorCycle(): void {
        const armorCycle: EEquipmentType[] = [
            EEquipmentType.Shoes,
            EEquipmentType.Leggings, 
            EEquipmentType.Belt,
            EEquipmentType.Armor,
            EEquipmentType.Helmet,
            EEquipmentType.Shoes // 循环回到起点
        ];

        this.activateCycle(armorCycle, "防具循环");
    }

        // 饰品循环：武器 -> 玉佩 -> 戒指 -> 护腕 -> 项链
    private activateAccessoryCycle(): void {
        const accessoryCycle: EEquipmentType[] = [
            EEquipmentType.Weapon,
            EEquipmentType.Pendant, // 假设玉佩对应Pendant
            EEquipmentType.Ring, // 
            EEquipmentType.Bracers, // 
            EEquipmentType.Necklace, // 假设项链对应Necklace
            EEquipmentType.Weapon // 循环回到起点
        ];

        this.activateCycle(accessoryCycle, "饰品循环");
    }

        // 跨循环：帽子 -> 武器，衣服 -> 项链，腰带 -> 护腕，裤子 -> 戒指，鞋 -> 玉佩
    private activateCrossCycle(): void {
        const crossPairs: [EEquipmentType, EEquipmentType][] = [
            [EEquipmentType.Helmet, EEquipmentType.Weapon],    // 帽子 -> 武器
            [EEquipmentType.Armor, EEquipmentType.Necklace],    // 衣服 -> 项链（假设项链对应Pendant）
            [EEquipmentType.Belt, EEquipmentType.Bracers],     // 腰带 -> 护腕
            [EEquipmentType.Leggings, EEquipmentType.Ring], // 裤子 -> 戒指（假设戒指对应Bracers）
            [EEquipmentType.Shoes, EEquipmentType.Pendant],     // 鞋 -> 玉佩（假设玉佩对应Pendant）
            [EEquipmentType.Weapon, EEquipmentType.Leggings],     // 鞋 -> 玉佩（假设玉佩对应Pendant）
            [EEquipmentType.Pendant, EEquipmentType.Belt],     // 鞋 -> 玉佩（假设玉佩对应Pendant）
            [EEquipmentType.Ring, EEquipmentType.Armor],     // 鞋 -> 玉佩（假设玉佩对应Pendant）
            [EEquipmentType.Bracers, EEquipmentType.Helmet],     // 鞋 -> 玉佩（假设玉佩对应Pendant）
            [EEquipmentType.Necklace, EEquipmentType.Shoes]     // 鞋 -> 玉佩（假设玉佩对应Pendant）
        ];

        for (const [fromType, toType] of crossPairs) {
            this.activatePair(fromType, toType, "跨循环");
        }
    }

        // 通用的循环激活方法
    private activateCycle(cycle: EEquipmentType[], cycleName: string): void {
        for (let i = 0; i < cycle.length - 1; i++) {
            const fromType = cycle[i];
            const toType = cycle[i + 1];
            this.activatePair(fromType, toType, cycleName);
        }
    }

        // 激活一对装备的五行词缀
    private activatePair(fromType: EEquipmentType, toType: EEquipmentType, relationName: string): void {
        const fromEquipment = this.equipped.get(fromType);
        const toEquipment = this.equipped.get(toType);

        if (!fromEquipment || !toEquipment) {
            console.log(`${relationName}: ${fromType} 或 ${toType} 未装备`);
            return;
        }

        if (this.isGeneratingRelation(fromEquipment.wuxing, toEquipment.wuxing)) {
            console.log(`${relationName}: ${fromType}(${fromEquipment.wuxing}) 生 ${toType}(${toEquipment.wuxing})`);
            this.activateOneAffix(toEquipment);
        } else {
            console.log(`${relationName}: ${fromType}(${fromEquipment.wuxing}) 与 ${toType}(${toEquipment.wuxing}) 无相生关系`);
        }
    }

        // 检查五行相生关系
    private isGeneratingRelation(fromWuxing: EWuxing, toWuxing: EWuxing): boolean {
        // 五行相生：金生水，水生木，木生火，火生土，土生金
        const generatingRelations: Record<EWuxing, EWuxing> = {
            [EWuxing.Jin]: EWuxing.Shui,   // 金生水
            [EWuxing.Shui]: EWuxing.Mu,    // 水生木  
            [EWuxing.Mu]: EWuxing.Huo,     // 木生火
            [EWuxing.Huo]: EWuxing.Tu,     // 火生土
            [EWuxing.Tu]: EWuxing.Jin      // 土生金
        };

        return generatingRelations[fromWuxing] === toWuxing;
    }

        // 激活一个装备的一条五行词缀
    private activateOneAffix(equipment: Equipment): void {
        if (!equipment.affixes_wuxing || equipment.affixes_wuxing.length === 0) {
            console.log(`装备 ${equipment.name} 没有五行词缀可激活`);
            return;
        }

        // 找到第一个未激活的词缀并激活
        for (const affix of equipment.affixes_wuxing) {
            if (!affix.isActive) {
                affix.isActive = true;
                console.log(`激活装备 ${equipment.name} 的五行词缀: ${affix.description}`);
                return;
            }
        }

        console.log(`装备 ${equipment.name} 的所有五行词缀都已激活`);
    }



}